package com.dbq.fast.business.login.api;

import android.text.TextUtils;
import android.util.Log;

import com.dbq.fast.App;
import com.dbq.fast.R;
import com.dbq.fast.business.login.bean.CustomProfile;
import com.dbq.fast.business.login.bean.TokenInfo;
import com.dbq.fast.business.login.bean.WeChatProfile;
import com.dbq.fast.business.login.bean.WeChatToken;
import com.dbq.fast.business.product.api.CommonTransformer;
import com.dbq.fast.common.bean.User;
import com.dbq.fast.common.json.GsonT;
import com.dbq.fast.common.manager.DatabaseManager;
import com.dbq.fast.common.net.HttpManager;
import com.dbq.fast.common.net.HttpResult;
import com.dbq.fast.common.net.RemoteApiCallBack;
import com.dbq.fast.wxapi.WXEntryActivity;
import com.yiba.vpn.utils.Constants;
import com.yiba.vpn.utils.RxBus;

import okhttp3.RequestBody;


public class LoginApi {

    private static HttpManager httpMgrWechat = WeChatManager.getInstance(); //wechat域名
    private static HttpManager httpMgrServer = HttpManager.getInstance(); //服务器域名

    //获取WeChat的access_token
    public static void getWCToken(String code, final RemoteApiCallBack<WeChatToken> c) {
        httpMgrWechat.getHttpService()
                .getWCToken(WXEntryActivity.APP_ID,WXEntryActivity.APP_SECRET,code,"authorization_code")
                .compose(new CommonTransformer<>())
                .subscribe(weChatToken -> {
                    Log.e("vpn_log", "getWCToken:" + weChatToken.toString());
                    c.onSuccess(weChatToken);
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    //获取WeChat的用户信息
    public static void getWCProfile(String token, String openId, final RemoteApiCallBack<WeChatProfile> c) {
        httpMgrWechat.getHttpService().getWCProfile(token, openId)
                .compose(new CommonTransformer<>())
                .subscribe(weChatProfile -> {
                    Log.e("vpn_log", "getWCProfile:" + weChatProfile.toString());
                    c.onSuccess(weChatProfile);
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    //获取服务器端返回的用户登录信息
    public static void getUserInfo(CustomProfile profile, final RemoteApiCallBack<CustomProfile> c) {
        String bodyStr = GsonT.toJson(profile);
        Log.e("vpn_log", "body:"+bodyStr);
        RequestBody body = httpMgrServer.getPostBody(bodyStr);
        httpMgrServer.getHttpService()
                .getUserInfo(111, profile.getParentId(), body)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    if (result.isSuccess()) {
                        CustomProfile temp = result.getData();
                        profile.setToken(temp.getToken());
                        profile.setAccount(temp.getAccount());
                        profile.setUserServiceLevel(temp.getUserServiceLevel());
                        profile.setNewTestService(temp.getNewTestService());
                        profile.setVpnId(temp.getVpnId());
                        profile.setRefreshToken(temp.getRefreshToken());
                        profile.setExpiresIn(temp.getExpiresIn());
                        profile.setNewUserDiscount(temp.getNewUserDiscount());
                        c.onSuccess(profile);
                    } else {
                        c.onFail(result.getCode(), App.getContext().getString(R.string.tip_retry_network_bad));
                    }
                }, throwable -> {
                    c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                });
    }

    //退出登录
    public static void logOut() {
        String token = User.getInstance().getToken();
        if (TextUtils.isEmpty(token)) return;
        httpMgrServer.getHttpService().logOut(token)
                .compose(new CommonTransformer<>())
                .subscribe(result -> {
                    Log.e("vpn_log", "result:" + result);
                }, throwable -> {});
    }

    //刷新token
    public static void refreshToken(boolean needReLogin, RemoteApiCallBack<Boolean> c) {
        synchronized (LoginApi.class) {
            CustomProfile profile = DatabaseManager.getInstance().queryProfile();
            if (profile == null) return;
            String refreshToken = profile.getRefreshToken();
            httpMgrServer.getHttpService().refreshToken(refreshToken)
                    .compose(new CommonTransformer<>())
                    .subscribe(result -> {
                        Log.e("vpn_log", "code:"+result.getCode()+" result:" + result.getData().toString());
                        int code = result.getCode();
                        if (code == 200) {
                            TokenInfo tokenInfo = result.getData();
                            profile.setToken(tokenInfo.getToken());
                            profile.setRefreshToken(tokenInfo.getRefreshToken());
                            profile.setExpiresIn(tokenInfo.getExpiresIn());
                            DatabaseManager.getInstance().saveProfile(profile);
                            User.getInstance().setToken(tokenInfo.getToken());
                            c.onSuccess(true);
                        } else if(code == 4014){
                            //跳登录页，重新登录
                            if(needReLogin) {
                                RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_REFRESH_TOKEN_FAIL);
                            }
                        } else {
                            c.onFail(code, App.getContext().getString(R.string.tip_retry_network_bad));
                        }
                    }, throwable -> {
                        c.onFail(-1, App.getContext().getString(R.string.tip_retry_network_error));
                    });
        }
    }

    //刷新token(同步方式，需自己起线程调用)
    public static String refreshTokenSync(boolean needReLogin) {
        synchronized (LoginApi.class) {
            CustomProfile profile = DatabaseManager.getInstance().queryProfile();
            if (profile == null) return "";
            String refreshToken = profile.getRefreshToken();
            try {
                HttpResult<TokenInfo> result = httpMgrServer.getHttpService().refreshTokenSync(refreshToken).execute().body();
                if (result.getCode() == 200) {
                    TokenInfo tokenInfo = result.getData();
                    profile.setToken(tokenInfo.getToken());
                    profile.setRefreshToken(tokenInfo.getRefreshToken());
                    profile.setExpiresIn(tokenInfo.getExpiresIn());
                    DatabaseManager.getInstance().saveProfile(profile);
                    User.getInstance().setToken(tokenInfo.getToken());
                    return tokenInfo.getToken();
                }else if(result.getCode() == 4014){
                    //跳登录页，重新登录
                    if(needReLogin) {
                        RxBus.get().post(Constants.RXBUS_START_VPN, Constants.RXBUS_REFRESH_TOKEN_FAIL);
                    }
                }

                return "";
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }
    }

}
